<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_News_Controllers_Article extends Gio_Core_Controller
{
	public function init()
	{
		$request = $this->getRequest();
		/**
		 * Register hooks
		 */
		Gio_Core_Hook_Registry::getInstance()->register('News_Article_Add_ShowSidebar', array(
			new Modules_News_Hooks_Articlerelates_Hook(), 
			'show'
		));
		
		Gio_Core_Hook_Registry::getInstance()->register('News_Article_Edit_ShowSidebar', array(
			new Modules_News_Hooks_Articlerelates_Hook(), 
			'show', 
			array($request->getParam('article_id'))
		));
		
		Gio_Core_Hook_Registry::getInstance()->register('News_Article_Add_ShowSidebar', array(
			new Modules_Tag_Hooks_Tagger_Hook(), 
			'show', 
			array('article_id', 'news_article_details', 'news_tag_article')
		));
		
		Gio_Core_Hook_Registry::getInstance()->register('News_Article_Edit_ShowSidebar', array(
			new Modules_Tag_Hooks_Tagger_Hook(), 
			'show', 
			array('article_id', 'news_article_details', 'news_tag_article', $request->getParam('article_id'))
		));
		
		Gio_Core_Hook_Registry::getInstance()->register(
			'News_Article_Add_Success',
			'Modules_News_Hooks_Articlerelates_Hook::add'
		);
		Gio_Core_Hook_Registry::getInstance()->register(
			'News_Article_Edit_Success',
			'Modules_News_Hooks_Articlerelates_Hook::add'
		);
		
		Gio_Core_Hook_Registry::getInstance()->register(
			'News_Article_Add_Success',
			'Modules_Tag_Hooks_Tagger_Hook::add'
		);
		Gio_Core_Hook_Registry::getInstance()->register(
			'News_Article_Edit_Success',
			'Modules_Tag_Hooks_Tagger_Hook::add'
		);
	}
	
	public function categoryAction()
	{
		$request = $this->getRequest();
				
		$category 	= Modules_Category_Services_Category::factory();
		
		if (null == $category) {
			Modules_Core_Services_Exception::error('ROUTE_NOT_FOUND');
		}
		
		$this->view->category = $category;
		if ($category['meta']) {
			$this->view->headMeta($category['meta']);
		}
		
		$perPage = 30;
		$pageIndex = (int)$request->getParam('page_index');
		if (null == $pageIndex || '' == $pageIndex || $pageIndex < 0) {
			$pageIndex = 1;
		}
		$start = ($pageIndex - 1) * $perPage;
		$this->view->pageIndex = $pageIndex;
		
		$this->view->articleDao = new Modules_News_Models_Mysql_Article();
		
		$condition = array(
					'status' 		=> 'active',
					'category_id'	=> $category['category_id'],
		);
				
		$articles = Modules_News_Services_Article::find($start, $perPage, $condition);
		$numArticles = Modules_News_Services_Article::count($condition);
		
		$this->view->articles = $articles; 
		$this->view->topArticle = ($articles) ? $articles[0] : null;
		
		// Pager
		require_once LIB_DIR . DS . 'PEAR' . DS . 'Pager' . DS . 'Sliding.php';
		$pagerPath = $this->view->url('news_article_category', $category);
		$pagerOptions = array(
			'mode'       	=> 'Sliding',
			'append'   		=> false,
    		'perPage'    	=> $perPage,
    		'delta'      	=> 3,
			'urlVar'		=> 'page',
			'path'			=> $pagerPath,
			'fileName'		=> 'page-%d',
			'separator'		=> '',
			'nextImg' 		=> '<small class="icon arrow_right"></small>',
			'prevImg'		=> '<small class="icon arrow_left"></small>',
			'altNext'		=> '',
			'altPrev'		=> '',
			'altPage'		=> '',
    		'totalItems' 	=> $numArticles,
			'currentPage'	=> $pageIndex,
			'urlSeparator'	=> '/',
			'spacesBeforeSeparator' => 0,
			'spacesAfterSeparator' => 0,
			'curPageSpanPre' => '<a href="javascript: void();" class="current">',
			'curPageSpanPost' => '</a>'
		
		);
		$pager = new Pager_Sliding($pagerOptions);
		$this->view->pager = $pager;
		$linkTagsRaw = $pager->linkTagsRaw;
		$this->view->linkTagsRaw = $linkTagsRaw;
	}
	
	public function detailsAction()
	{
		$request = $this->getRequest();
		$articleId = $request->getParam('article_id');
		
		$article 	= Modules_News_Services_Article::getById($articleId, true);
		if (null == $article) {
			Modules_Core_Services_Exception::error('ROUTE_NOT_FOUND');
		}
		
		/**
		 * Format content
		 */
		$article['content'] = Gio_Core_Hook_Registry::getInstance()->executeFilter('News_Article_Details_FormatContent', $article['content'], array($article['web_id']));
		
		$this->view->article = $article;
		
		$string = new Gio_Core_String();
		
		$this->view->metaKeyword = $string->escape($article['title']) . ' ' . Gio_Core_String::removeSign($article['title'], ' ');
		
		$description = strip_tags($article['description']);
		$description = trim($description);
		$descriptionRemoveSign = Gio_Core_String::removeSign($description, '');
		$this->view->metaDescription = $string->escape($description) . ''
										. $descriptionRemoveSign;

		/**
		 * Increase article views
		 */
		Modules_News_Services_Article::increaseViews($article);
	}
	
	public function searchAction()
	{
	}
	
	public function suggestAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		$q 		 = $request->getParam('q');
		$q		 = Gio_Core_String::stripTags($q, array('.'));
		$limit 	 = $request->getParam('limit', 10);
		$limit   = ((int)$limit) ? $limit : 10;
		
		if (null == $q) {
			return;
		}
		
		$condition = array(
						'keyword' => $q,
						'status'  => 'active'		
		);
		$articles    = Modules_News_Services_Article::find(0, $limit, $condition);
		$return  = '';
		foreach ($articles as $article) {
			$return .= $article['title'] . '|' . $article['article_id']
							 . '|' . $this->view->url('news_article_details', $article) . "\n";
		}
		
		$this->getResponse()->setBody($return);
	}
	
	/* ############################# Backend ################################ */
	
	/**
	 * Activate news article
	 */
	public function activateAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			return;
		}
		$response = 'RESULT_NOT_OK';
		$articleId = $request->getPost('article_id');
		$article = Modules_News_Services_Article::getById($articleId);
		
		if (null == $article){
			$this->getResponse()->setBody($response);
			return;	
		}
		
		$act = $request->getPost('act');
		switch ($act) {
			case 'activate':
				$status = 'active';
				break;
			case 'deactivate':
				$status = 'inactive';
				break;
		}
		$article['status'] = $status;
		$response = 'RESULT_OK';
		Modules_News_Services_Article::activate($article);
		$this->getResponse()->setBody($response);
	}
	
	/**
	 * Add news article
	 */
	public function addAction()
	{
		$request = $this->getRequest();
		$this->view->lang		   	  = $request->getParam('lang');
		
		$configs = Gio_Core_Config_Xml::getConfig('web');
		$this->view->frontendTemplate = $configs->template;
		$this->view->frontendSkin 	  = $configs->skin;
		
		$sourceId      = $request->getParam('source_id');
		$sourceArticle = (null == $sourceId) ? null : Modules_News_Services_Article::getById($sourceId);
		$this->view->sourceArticle = $sourceArticle;
		
		/**
		 * Web source
		 */
		$webSource 					  = Modules_News_Services_Web::getAllWebs();
		$this->view->webSource 	  	  = $webSource;
		
		if ($request->isPost()) {
			$user = Gio_Core_Session::getUser();
			
			$articleData = $request->getPost('article');
			$articleData = Modules_News_Services_Article::validate($articleData);
			
			if (isset($articleData['messages_error']) && $articleData['messages_error']) {
				$this->view->errorMessages = $articleData['messages'];
				$this->view->articleData = $articleData;
				return;
			}
			
			$hotArticle = (isset($articleData['article_hot']) && $articleData['article_hot'] == 1)
										? 1 : 0; 
			$photoArticle = (isset($articleData['article_photo']) && $articleData['article_photo'] == 1)
										? 1 : 0;
			$videoArticle = (isset($articleData['article_video']) && $articleData['article_video'] == 1)
										? 1 : 0;
			
			$article = array(
				'title'			=> $this->view->STRING->escape($articleData['title']),
				'slug'			=> $this->view->STRING->escape($articleData['slug']),
				'description'	=> $articleData['description'],
				'content'		=> $articleData['content'],
				'status'		=> ($articleData['status'] == 'active') ? 'active' : 'inactive',
				'category_id'	=> $articleData['category_id'],
				'web_id'		=> $articleData['web_id'],
				'link_source'	=> $this->view->STRING->escape($articleData['link_source']),
				'created_date'  => date('Y-m-d H:i:s'),
				'user_id'		=> $user['user_id'],
				'image_url_data'=> $articleData['image_url_data'],
				'image_url'		=> $this->view->STRING->escape($articleData['image_url']),
				'article_hot' 	=> $hotArticle,
				'article_photo' => $photoArticle,
				'article_video' => $videoArticle,
				'language'		=> $articleData['language'],
				'author'		=> $this->view->STRING->escape($articleData['author']),
			);
			
			$sourceItem = isset($articleData['source_item']) 
								? $articleData['source_item'] : null;
			$categories = $request->getPost('categories');
								
			$id 	 = Modules_News_Services_Article::add($article, $categories, $sourceItem);
			
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('article_add_success'));
			$this->redirect($this->view->url('news_article_add'));
		}
	} 
	
	/**
	 * Delete news article
	 */
	public function deleteAction()
	{
		$this->setNoRender();
		$this->disableLayout();
		
		$request = $this->getRequest();
		if (!$request->isPost()) {
			return;
		}
		$response = 'RESULT_NOT_OK';
		$articleId = $request->getPost('article_id');
		$article = Modules_News_Services_Article::getById($articleId);
		
		if (null == $article){
			$this->getResponse()->setBody($response);
			return;	
		}
		
		$article['status'] = 'deleted';
		$response = 'RESULT_OK';
		Modules_News_Services_Article::update($article);
		$this->getResponse()->setBody($response);
	}
	
	/**
	 * Edit news article
	 */
	public function editAction()
	{
		$request 		  = $this->getRequest();
		$this->view->lang = $request->getParam('lang');
		$articleId 		  = $request->getParam('article_id');
		$article		  = Modules_News_Services_Article::getById($articleId);
		
		$configs = Gio_Core_Config_Xml::getConfig('web');
		$this->view->frontendTemplate = $configs->template;
		$this->view->frontendSkin 	  = $configs->skin;
		
		if (null == $article) {
			Modules_Core_Services_Exception::error('DATA_NOT_FOUND');
		}
		
		$this->view->categories  = Modules_News_Services_Article::getCategoryIds($article);
		$this->view->articleData = $article;
		
		/**
		 * Get source item
		 */
		$this->view->sourceArticle = Modules_News_Services_Article::getSource($article);
		
		/**
		 * Web source
		 */
		$webSource 					  = Modules_News_Services_Web::getAllWebs();
		$this->view->webSource 	  	  = $webSource;
		
		if ($request->isPost()) {
			$user = Gio_Core_Session::getUser();
			
			$articleData = $request->getPost('article');
			$articleData = Modules_News_Services_Article::validate($articleData);
			
			if (isset($articleData['messages_error']) && $articleData['messages_error']) {
				$this->view->errorMessages = $articleData['messages'];
				$this->view->articleData = $articleData;
				return;
			}
			
			$hotArticle = (isset($articleData['article_hot']) && $articleData['article_hot'] == 1)
										? 1 : 0; 
			$photoArticle = (isset($articleData['article_photo']) && $articleData['article_photo'] == 1)
										? 1 : 0;
			$videoArticle = (isset($articleData['article_video']) && $articleData['article_video'] == 1)
										? 1 : 0;
			
			$article = array(
				'article_id'	=> $articleId,
				'title'			=> $this->view->STRING->escape($articleData['title']),
				'slug'			=> $this->view->STRING->escape($articleData['slug']),
				'description'	=> $articleData['description'],
				'content'		=> $articleData['content'],
				'status'		=> ($articleData['status'] == 'active') ? 'active' : 'inactive',
				'category_id'	=> $articleData['category_id'],
				'web_id'		=> $articleData['web_id'],
				'link_source'	=> $this->view->STRING->escape($articleData['link_source']),
				'image_url_data'=> $articleData['image_url_data'],
				'image_url'		=> $this->view->STRING->escape($articleData['image_url']),
				'article_hot' 	=> $hotArticle,
				'article_photo' => $photoArticle,
				'article_video' => $videoArticle,
				'language'		=> $articleData['language'],
				'author'		=> $this->view->STRING->escape($articleData['author']),
			);
			
			$sourceItem = isset($articleData['source_item']) 
								? $articleData['source_item'] : null;
			$categories = $request->getPost('categories');
			
			Modules_News_Services_Article::update($article, $categories, $sourceItem);
			
			Gio_Core_Messenger::getInstance()
								->addMessage($this->view->TRANSLATOR->translator('article_edit_success'));
			$this->redirect($this->view->url('news_article_edit', $article));
		}
	}
	
	/**
	 * List news articles
	 */
	public function listAction()
	{
		$request = $this->getRequest();
		$lang    = $request->getParam('lang');
		$this->view->lang = $lang;
		$paramLang = ($lang) ? '/' . $lang : null;
		
		$perPage = 20;
		$pageIndex = (int)$request->getParam('page_index');
		if (null == $pageIndex || '' == $pageIndex || $pageIndex < 0) {
			$pageIndex = 1;
		}
		$start = ($pageIndex - 1) * $perPage;
		$this->view->pageIndex = $pageIndex;
		
		$this->view->articleDao = new Modules_News_Models_Mysql_Article();
		
		$user = Gio_Core_Session::getUser();
		
		$condition = array(
						'status' 			=> 'active',
						'created_date_from' => date('Y-m-d 00:00:00'),
						'created_date_to'   => date('Y-m-d H:i:s'),
						'search_form'		=> false,
						'user_id' 			=> $user['user_id'],
						'search_my_articles'=> true,
		);
		$json = new Services_JSON();
		if ($request->isPost()) {
			$condition = $request->getPost('condition');
			$createdDateFrom = $request->getPost('created_date_from');
			$fromHour = (isset($createdDateFrom['hour']) && $createdDateFrom['hour']) 
									? $createdDateFrom['hour'] : date('H');
			$fromMinute = (isset($createdDateFrom['minute']) && $createdDateFrom['minute']) 
									? $createdDateFrom['minute'] : date('i');
			$fromSecond = (isset($createdDateFrom['second']) && $createdDateFrom['second']) 
									? $createdDateFrom['second'] : date('s');
			$fromDay = (isset($createdDateFrom['day']) && $createdDateFrom['day']) 
									? $createdDateFrom['day'] : date('d');
			$fromMonth = (isset($createdDateFrom['month']) && $createdDateFrom['month']) 
									? $createdDateFrom['month'] : date('m');
			$fromYear = (isset($createdDateFrom['year']) && $createdDateFrom['year']) 
									? $createdDateFrom['year'] : date('Y');
			$condition['created_date_from'] = date('Y-m-d H:i:s', strtotime("$fromYear-$fromMonth-$fromDay $fromHour:$fromMinute:$fromSecond")); 
			
			$createdDateTo = $request->getPost('created_date_to');
			$toHour = (isset($createdDateTo['hour']) && $createdDateTo['hour']) 
									? $createdDateTo['hour'] : date('H');
			$toMinute = (isset($createdDateTo['minute']) && $createdDateTo['minute']) 
									? $createdDateTo['minute'] : date('i');
			$toSecond = (isset($createdDateTo['second']) && $createdDateTo['second']) 
									? $createdDateTo['second'] : date('s');
			$toDay = (isset($createdDateTo['day']) && $createdDateTo['day']) 
									? $createdDateTo['day'] : date('d');
			$toMonth = (isset($createdDateTo['month']) && $createdDateTo['month']) 
									? $createdDateTo['month'] : date('m');
			$toYear = (isset($createdDateTo['year']) && $createdDateTo['year']) 
									? $createdDateTo['year'] : date('Y');
			$condition['created_date_to'] = date('Y-m-d H:i:s', strtotime("$toYear-$toMonth-$toDay $toHour:$toMinute:$toSecond"));
			$condition['search_form'] = true;
			
			/**
			 * Search in my articles 
			 */
			$searchMyArticles = (isset($condition['search_my_articles']) && $condition['search_my_articles'] == 1)
														? true : false;
			$condition['user_id'] = ($searchMyArticles) ? $user['user_id'] : null;
			
			$params = rawurlencode(base64_encode($json->encodeUnsafe($condition)));
		} else {
			$params = $request->getParam('q');
			($params != null)
				? ($condition = (array)$json->decode(rawurldecode(base64_decode($params))))
				: ($params = rawurlencode(base64_encode($json->encodeUnsafe($condition))));
		}

		$params = (empty($condition)) ? null : $params;
		$this->view->condition = $condition;
		
		$articles = Modules_News_Services_Article::find($start, $perPage, $condition);
		$numArticles = Modules_News_Services_Article::count($condition);
		
		$this->view->articles = $articles; 
		
		// Pager
		require_once LIB_DIR . DS . 'PEAR' . DS . 'Pager' . DS . 'Sliding.php';
		$pagerPath = $this->view->url('news_article_list');
		$pagerOptions = array(
			'mode'       	=> 'Sliding',
			'append'   		=> false,
    		'perPage'    	=> $perPage,
    		'delta'      	=> 3,
			'urlVar'		=> 'page',
			'path'			=> $pagerPath,
			'fileName'		=> (null == $params) ? 'page-%d' . $paramLang : 'page-%d' . $paramLang . '/?q=' . $params,
			'separator'		=> '',
			'nextImg' 		=> '<small class="icon arrow_right"></small>',
			'prevImg'		=> '<small class="icon arrow_left"></small>',
			'altNext'		=> '',
			'altPrev'		=> '',
			'altPage'		=> '',
    		'totalItems' 	=> $numArticles,
			'currentPage'	=> $pageIndex,
			'urlSeparator'	=> '/',
			'spacesBeforeSeparator' => 0,
			'spacesAfterSeparator' => 0,
			'curPageSpanPre' => '<a href="javascript: void();" class="current">',
			'curPageSpanPost' => '</a>'
		
		);
		$pager = new Pager_Sliding($pagerOptions);
		$this->view->pager = $pager;
	}
}